﻿package com.thorqq.magictimer.action;

import com.baidu.mobstat.StatService;
import com.thorqq.magictimer.Configuration;
import com.thorqq.magictimer.StatHelper;
import com.thorqq.magictimer.core.TAction;
import com.thorqq.magictimer.core.TTimerLog;
import com.thorqq.magictimer.db.DBHelper;
import com.thorqq.magictimer.timeLoop.Timer;
import com.thorqq.magictimer.timeLoop.TimerMgr;
import com.thorqq.magictimer.util.DateUtil;
import com.thorqq.magictimer.util.Util;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;

public class ActionMain extends Service
{

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Util.log("ActionMain.onStartCommand");
        if (intent == null) {
            stopSelf();
            return START_NOT_STICKY;
        }

        final Timer timer = intent.getParcelableExtra(
                TimerMgr.ALARM_INTENT_EXTRA);

        if (timer == null) {
            stopSelf();
            return START_NOT_STICKY;
        }
        
        //执行所有动作
//        ActionMgr.getIntance().run(this, timer);
        for (TAction action : timer.getTActions())
        {
            //打印日志
            Util.log("Action run: " + action.getActionType() + "|" + action.toString());
            //记录统计信息
            StatService.onEvent(this, StatHelper.EVENT_ID_ACTION_RUN, action.getName());
            //记录执行日志
            TTimerLog timerLog = new TTimerLog();
            timerLog.start_time = DateUtil.MillisToStr(System.currentTimeMillis());
            timerLog.timer_id = timer.getID();
            timerLog.timer_name = timer.getName();
            timerLog.action_name = action.getName();
            timerLog.action_desc = (action.getDescription() == null ? "" : action.getDescription());
            new TimerLogOperator().execute(timerLog);

            action.run(this, timer);
            
        }

        
        return START_STICKY;
    }

    public class TimerLogOperator extends AsyncTask<TTimerLog, Void, Void>
    {
        @Override
        protected Void doInBackground(TTimerLog... params) 
        {
            //先插入新的记录
            DBHelper.getIntance().insertTimerLog(params[0]);
            
            //然后删除过期的记录
            int recNum = Configuration.getIntance().getTimerLogNum();
            if(recNum > 0)
            {
                DBHelper.getIntance().deleteTimerLog(recNum);
            }
            return null;
        }
        
        @Override
        protected void onProgressUpdate(Void... b )
        {
        }

        @Override
        protected void onPostExecute(Void result) 
        {
        }
    }
}
